#coding:utf-8


from twisted.internet import reactor, defer, threads
from twisted.internet.protocol import Protocol, Factory, DatagramProtocol
import base
from datamethod import *
from core import logging

class UDPDataDealMixin(base.BaseDataDeal):
    
    def unpack(self, data):
        data = hex2data(data)
        return data
    
    def pack(self, data):
        checksum = getchecksum(data)
        data.insert(0, checksum)
        return data2hex(data)
    
    def deal(self, data, addr):
        data = self.unpack(data)
        self.separate_data(data, addr)
    
    
class UDPServer(DatagramProtocol, UDPDataDealMixin):
    def __init__(self, player):
        self.player = player
    
    def datagramReceived(self, data, addr):
        logging.log("DATAUDP Recv 【IP:%15s PORT:%5s】(0):%s"%(addr[0],addr[1], hex2str(data)))
        self.deal(data, addr)
        
    def send(self, data, addr):
        data = self.pack(data)
        self.transport.write(data, addr)
        logging.log("DATAUDP Send 【IP:%15s PORT:%5s】(0):%s"%(addr[0],addr[1], hex2str(data)))
        
    def logonRequest(self, tel, addr):
        #report.info("%s udp login: %s"%(addr, tel))
        if self.player.getConnector(tel):
            self.send([0x10, 0x91, 0x01], addr)
        else: # 找不到对应的手机号,UDP登录失败
            self.send([0x10, 0x91, 0x02], addr)
    
    def bussDataReceived(self, data, addr):
        tel = (data2asc(data[2:17])).strip()
        bussdata = data[:2] + data[17:]
        self.player.bussDataReceived(tel, bussdata)
    
    def linkReceived(self, data, addr):
        pass
    
    def logoutRequest(self, data, addr):
        pass
    
    